package com.usian.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.constants.BehaviorConstant;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.AuthorFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserRelationService;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserRelationServiceImpl extends BaseServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserRelationService {
    @Autowired
    private ApUserFanMapper apUserFanMapper;

    @Autowired
    private AuthorFeign authorFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto == null || dto.getAuthorId() == null || dto.getOperation() == null) return paramError;
        if (dto.getOperation() != 0 && dto.getOperation() != 1) return paramError;
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return needLogin;
        //查询作者信息
        ApAuthor author = authorFeign.getByAuthorId(dto.getAuthorId());

        ApUserFollow userFollow = getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, author.getUserId()));
        ApUserFan userFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, userId).eq(ApUserFan::getUserId, author.getUserId()));

        if (dto.getOperation() == 0) {
            if (userFollow == null) {//之前没有关注
                ApUserFollow follow = new ApUserFollow();
                follow.setUserId(userId);
                //用户和用户的关系
                follow.setFollowId(author.getUserId());
                follow.setFollowName(author.getName());
                follow.setCreatedTime(new Date());
                follow.setIsNotice(true);
                follow.setLevel((short) 1);
                save(follow);
            }
            if (userFan == null) {
                ApUser apUser = apUserMapper.selectById(userId);
                ApUserFan fan = new ApUserFan();
                fan.setFansName(apUser.getName());//关注人的名字
                fan.setFansId(userId.longValue());
                fan.setUserId(author.getUserId());
                fan.setCreatedTime(new Date());
                fan.setIsDisplay(true);
                fan.setIsShieldLetter(false);
                fan.setIsShieldComment(false);
                apUserFanMapper.insert(fan);
                rabbitTemplate.convertAndSend(BehaviorConstant.FOLLOW_BEHAVIOR_ROUTING_KEY);
            }
            // 记录关注行为
            FollowBehaviorDto behaviorDto = new FollowBehaviorDto();
            behaviorDto.setFollowId(author.getUserId());
            behaviorDto.setArticleId(dto.getArticleId());
            behaviorDto.setUserId(userId);
            //异步发送消息，保存关注行为
            rabbitTemplate.convertAndSend(BehaviorConstant.FOLLOW_BEHAVIOR_ROUTING_KEY,JSON.toJSONString(behaviorDto));
            return ResponseResult.okResult(0, "关注成功");
        } else {
            if (userFollow != null) removeById(userFollow.getId());
            if (userFan != null) apUserFanMapper.deleteById(userFan.getId());
            return ResponseResult.okResult(0, "取消关注成功");
        }
    }

    @Override
    public ApUserFollow getFollow(Integer userId, Integer authorUserId) {
        if (userId!=null && authorUserId!=null)return getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId,authorUserId).eq(ApUserFollow::getUserId,userId));
        return null;
    }
}
